package coffeenc.mall.admin.config;

import coffeenc.mall.admin.entity.UmsAdmin;
import coffeenc.mall.admin.entity.UmsResource;
import coffeenc.mall.admin.mapper.UmsAdminMapper;
import coffeenc.mall.admin.mapper.UmsResourceMapper;
import coffeenc.mall.admin.service.UmsAdminCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;

@Configuration
public class AdminUserDetailsService implements UserDetailsService {
    @Autowired
    private UmsAdminCacheService umsAdminCacheService;
    @Autowired
    private UmsAdminMapper adminMapper;
    @Autowired
    private UmsResourceMapper resourceMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UmsAdmin umsAdmin = getAdminByUsername(username);
        if (umsAdmin !=null){
            List<UmsResource> resourceList = getResourceList(umsAdmin.getId());
            return new AdminUserDetails(umsAdmin, resourceList);
        }
        throw new UsernameNotFoundException("用户不存在");
    }

    public UmsAdmin getAdminByUsername(String username){
        /**
         * 从redis缓存中读取
         */
        UmsAdmin umsAdmin = umsAdminCacheService.getAdmin(username);
        if (umsAdmin !=null) return umsAdmin;
        /**
         * 若缓存中不存在该用户，从mysql中读取
         */
        UmsAdmin example = new UmsAdmin();
        example.setUsername(username);
        List<UmsAdmin> umsAdminList = adminMapper.selectByCondition(example);
        if (umsAdminList ==null) return null;
        UmsAdmin admin = umsAdminList.get(0);
        /**
         * 若从mysql中读取到指定用户，写入redis缓存，然后返回UmsAdmin
         */
        umsAdminCacheService.setAdmin(username,admin);
        return admin;
    }

    public List<UmsResource> getResourceList(Long adminId){
        List<UmsResource> resourceList = umsAdminCacheService.getResourceList(adminId);  /* 从Redis中读取资源列表 */
        if (resourceList != null){
            return resourceList;
        }
        resourceList = resourceMapper.getResourceListByAdminId(adminId);  /* 从MySQL中读取资源列表 */
        if (resourceList != null){
            umsAdminCacheService.setResourceList(adminId,resourceList);
            return resourceList;
        }
        return null;
    }

    @Bean
    UserDetailsService userDetailsService(){
        return new AdminUserDetailsService();
    }
}
